#include"../source/socket.hpp"
#include"../source/server.hpp"
#include"../source/connection.hpp"
#include"../source/buffer.hpp"
#include"../source/acceptor.hpp"

/*用于管理所有的连接对象*/
std::unordered_map<uint64_t,PtrConnection> _conns;
uint64_t conn_id=0;

EventLoop loop;


void ConnectionDestroy(const PtrConnection& conn){
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection& conn){
    DLOG("NEW CONNECTION:%p",conn.get());
}

void MessageHandler(const PtrConnection&conn,Buffer*buffer){
    DLOG("%s",buffer->ReadPosition());
    buffer->MoveReadOffset(buffer->ReadAlbeSize());
    std::string str="hello";
    conn->Send(str.c_str(),str.size());
    // conn->Shutdown();
}

// void Acceptor(Channel* listen_channel,EventLoop*loop){
void NewConnection(int fd){
    // int fd=listen_channel->FD();
    // int newfd=accept(fd,NULL,NULL);
    // if(newfd<0) return;

    // Buffer* buffer;
    conn_id++;
    PtrConnection conn(new Connection(&loop,conn_id,fd));
    // conn->SetConnectedCallback(std::bind(OnConnected,conn));
    // conn->SetMessageCallback(std::bind(MessageHandler,conn,buffer));
    // conn->SetSrvClosedCallback(std::bind(ConnectionDestroy,conn));
    //经测试，上述不能这样写，要写成预留的，如果缓冲区是写死的，会出错
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->SetMessageCallback(std::bind(MessageHandler,std::placeholders::_1,std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy,std::placeholders::_1));
    
    conn->EnableInactiveRelease(10);//启动非活跃超时销毁功能
    conn->Establish();//就绪初始化

    _conns.insert(std::make_pair(conn_id,conn));
}
int main()
{   
    srand(time(NULL));
    //Poller poller;
    Acceptor acceptor(&loop,8081);
    /*Socket listen_socket;   
    listen_socket.CreateServer(8081);已封装进Acceptor*/
    acceptor.SetAccept(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();

    //在acceptor里面已经有channel在管理了，这里不用再设置
    //为监听套接字创建一个Channel进行事件的管理，以及事件的处理
    // Channel channel(listen_socket.Get_fd(),&loop);
    // channel.SetReadCallback(std::bind(Acceptor,&channel,&loop));//在回调中，获取新连接，为新连接创建Channel并添加监控
    // channel.EnableRead();//启动可读事件监控
    while(1){
        loop.Start();

        // std::vector<Channel*> actives;
        // poller.Poll(&actives);
        // for(auto &a:actives){
        //     a->HandleEvent();
        // }



        // int newfd=listen_socket.Accept();
        // if(newfd<0){
        //     DLOG("accept failed");
        //     continue;
        // }
        // Socket cli_socket(newfd);
        // char buffer[1024]={0};
        // int ret=cli_socket.Recv(buffer,sizeof(buffer)-1);
        // if(ret<0){
        //     cli_socket.Close();
        //     continue;
        // }
        // cli_socket.Send(buffer,ret);
        // cli_socket.Close();
    }
    // listen_socket.Close();
    return 0;
}